package com.bckj.freshnow.payment.pay.extension.wxpay.jsapi;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.cola.extension.Extension;
import com.bckj.freshnow.payment.entity.PayConfig;
import com.bckj.freshnow.payment.entity.PayMerchantConfig;
import com.bckj.freshnow.payment.model.PayRequest;
import com.bckj.freshnow.payment.model.PayResponse;
import com.bckj.freshnow.payment.pay.PaymentServiceManager;
import com.bckj.freshnow.payment.pay.extension.PayExtPt;
import com.bckj.freshnow.payment.pay.wxpay.WxJsapiPaymentService;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;
import lombok.RequiredArgsConstructor;

import java.math.BigDecimal;

@Extension(bizId = "PAY", useCase = "WX", scenario = "JSAPI")
@RequiredArgsConstructor
public class WxJsapiPayExtPt implements PayExtPt {

    private final PaymentServiceManager paymentServiceManager;

    @Override
    public PayResponse pay(PayRequest request) {
        WxJsapiPaymentService paymentService = (WxJsapiPaymentService) paymentServiceManager.getPaymentService(request.getAppId(), request.getPaymentMethod());
        JsapiService payService = (JsapiService) paymentService.getService();
        PrepayRequest wechatRequest = toWechatRequest(request);
        PayConfig payConfig = paymentService.getPaymentConfig().getPayConfig();
        PayMerchantConfig payMerchantConfig = payConfig.getPayMerchantConfig();
        wechatRequest.setMchid(payMerchantConfig.getOutMerchantId());
        try {
            PrepayResponse wechatResponse = payService.prepay(wechatRequest);
            return toPayResponse(wechatResponse);
        } catch (Exception e) {
            PayResponse response = new PayResponse();
            response.setCode(500);
            response.setMessage("WechatJsapi Error:" + e.getMessage());
            return response;
        }
    }

    private PrepayRequest toWechatRequest(PayRequest request) {
        PrepayRequest wechatRequest = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(NumberUtil.mul(request.getAmount(), new BigDecimal("100")).intValue());
        wechatRequest.setAmount(amount);
        wechatRequest.setAppid(request.getAppId());
        wechatRequest.setDescription(request.getDescribe());
        wechatRequest.setNotifyUrl(request.getNotifyUrl());
        wechatRequest.setOutTradeNo(request.getRequestNo());
        return wechatRequest;
    }

    private PayResponse toPayResponse(PrepayResponse wechatResponse) {
        PayResponse response = new PayResponse();
        response.setCode(200);
        response.setPrepayId(wechatResponse.getPrepayId());
        return response;
    }
}
